package com.lagou.order.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.lagou.order.pojo.Order;
import com.lagou.order.pojo.OrderVo;
import com.lagou.order.service.OrderService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;

/**
 * 订单控制类
 * @author yzh
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    /**
     * 订单服务对象
     */
    @Autowired
    private OrderService<Order> orderService;

    /**
     * RabbitMQ操作模板
     */
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 订单队列
     */
    @Autowired
    private Exchange exchange;

    /**
     * 订单队列绑定对象
     */
    @Autowired
    private Binding binding;

    /**
     * 获得新的订单号
     * @return 新订单号
     */
    @GetMapping("/getNewOrderId")
    public R getNewOrderId() {
        long newOrderId = 10000;
        try {
            newOrderId = orderService.getNewOrderId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok(newOrderId+1);
    }

    /**
     * 根据订单号获得订单
     * @param orderId 订单号
     * @return 订单
     */
    @GetMapping("/getOrderById/{orderId}")
    public R getOrderById(@PathVariable long orderId) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        Order order = orderService.getOne(queryWrapper);
        OrderVo orderVo = new OrderVo();
        BeanUtils.copyProperties(order, orderVo);
        long remainingTime = 1800 - ((LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"))) - (order.getOrderCreateTime().toEpochSecond(ZoneOffset.of("+8"))));
        System.out.println("-----------------------"+remainingTime+"--------------------------");
        orderVo.setRemainingTime(remainingTime - 1);
        return R.ok(orderVo);
    }

    /**
     * 创建订单
     * @return 创建结果
     */
    @GetMapping("/createOrder/{orderId}")
    public R createOrder(@PathVariable long orderId) {
        try {
            Order order = new Order();
            order.setOrderId(orderId);
            order.setOrderCreateTime(LocalDateTime.now());
            order.setOrderState(0);
            //保存订单
            orderService.save(order);
            //推送到订单消息队列
            Message message = MessageBuilder.withBody(("order."+orderId).getBytes()).build();
            rabbitTemplate.send(exchange.getName(), binding.getRoutingKey(), message);
            return R.ok("提交订单成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.failed("提交订单失败");
        }
    }

    /**
     * 监听订单死信队列进行订单处理
     * @param message 死信队列消息
     */
    @RabbitListener(queues = "q.biz.order.dlx")
    public void orderDeal(@Payload String message) {
        try {
            System.out.println(message);
            String orderIdStr = message.substring(message.indexOf(".") + 1);
            if(StringUtils.isNotEmpty(orderIdStr)) {
                long orderId = Long.parseLong(orderIdStr);
                //查询订单状态
                QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("order_id", orderId);
                Order order = orderService.getOne(queryWrapper);
                //如果订单没有支付，设置订单状态为-1（订单关闭-订单超时未支付）
                if (order != null && order.getOrderState() != 2) {
                    order.setOrderState(-1);
                    orderService.saveOrUpdate(order);
                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    /**
     * 订单支付的方法
     * @param orderId 订单号
     * @return 支付结果
     */
    @GetMapping("/pay/{orderId}")
    public R pay(@PathVariable long orderId) {
        try {
            //判断订单是否已支付
            QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", orderId);
            Order order = orderService.getOne(queryWrapper);
            //如果订单非关闭状态则将状态改为已支付
            if(order != null && order.getOrderState() != -1) {
                order.setOrderState(2);
                order.setOrderUpdateTime(LocalDateTime.now());
                orderService.saveOrUpdate(order);
            }
            return R.ok("订单支付成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.failed("订单支付失败");
        }
    }

    /**
     * 获取付款超时而取消的订单列表
     * @return 订单列表
     */
    @GetMapping("/getOrderListByTimeOut")
    public R getOrderListByTimeOut() {
        try {
            QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_state", -1);
            List<Order> orderList = orderService.list(queryWrapper);
            return R.ok(orderList);
        } catch (Exception e) {
            e.printStackTrace();
            return R.failed("获取失败");
        }
    }
}
